package me.qi.kancha.support;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;

/**
 * @author sun
 * @date 2022/10/26 23:02
 * @modified By：
 */
@Slf4j
@Component
public class TencentCOS {

    private COSClient cosClient;
    private final TencentYunProperties properties;

    public TencentCOS(TencentYunProperties properties) {
        this.properties = properties;
        cosClient = clientInit(properties.getSecretId(), properties.getSecretKey(), properties.getCosRegion());
    }

    private COSClient clientInit(String secretId, String secretKey, String region) {
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        // 2 设置 bucket 的地域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
        // clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
        Region regionObj = new Region(region);
        ClientConfig clientConfig = new ClientConfig(regionObj);
        // 这里建议设置使用 https 协议
        // 从 5.6.54 版本开始，默认使用了 https
        clientConfig.setHttpProtocol(HttpProtocol.https);
        // 3 生成 cos 客户端。
        return new COSClient(cred, clientConfig);
    }

    public String upload(File localFile, String key) {
        // 指定要上传的文件
        // 指定文件将要存放的存储桶
        // 指定文件上传到 COS 上的路径，即对象键。例如对象键为folder/picture.jpg，则表示将文件 picture.jpg 上传到 folder 路径下
        PutObjectRequest putObjectRequest = new PutObjectRequest(properties.getCosBucketName(), key, localFile);
        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
        return String.format("%s/%s", properties.getCosHost(), key);
    }
}
